package com.album.activity.pageView;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.album.R;
import com.album.activity.MessageDialog;
import com.album.activity.SetstateManager;
import com.album.activity.page.Page;
import com.album.activity.page.PageManager;
import com.album.bean.ErrorInfo;
import com.album.bean.FriendsInfo;
import com.album.bean.PicinfoList;
import com.album.bean.RondomUser;
import com.album.provider.ProviderUtil;
import com.album.task.DownImageTask;
import com.album.task.GetFriendsTask;
import com.album.task.GetPicinfolistTask;
import com.album.task.ICallBack;
import com.album.task.Task;
import com.album.utils.CommonUtil;
import com.album.utils.MyLog;
import com.google.gson.Gson;

public class MyFriendsView extends Page{
	private static String TAG = "CasualLookView";
	 /** 
    * 文件夹下的图片列表 
    */  
	private List<Integer> mImageList;
	private List<Integer> mImageList2;
	/**
	 * 好友头像
	 */
	private List<Integer> myFriendsList;
	private ListView casualListView;
	private HorizontalScrollView scrollView;
	private Gson gson;
	private Context ctx;
	private String username;//用户名

	private static final int FRIEND_INFO = 111;
	private static final int FRIEND_FAIL = 112;
	private static final int FRIEND_NO = 115;
	
	private static final int PICINFOLIST_RE_MYPTO_IMAGE = 117;
	private static final int PICINFOLIST_DOWN_IMAGE_FAIL = 118;
	private static final int PICINFOLIST_INFO = 119;
	private static final int PICINFOLIST_INFO_FAIL = 200;

	private static final int TIME_OUT = 11;
	private static final int INTENT_ERROR = 12;
	private static final int HTTP_ERROR = 13;
	private ProgressDialog dialog_1;
	
	/*
	 * 存放用户头像、昵称、时间、相片
	 */
	private List<FriendsInfo> friendList = new ArrayList<FriendsInfo>();
	private HashMap<String,List<PicinfoList>> userMap = new HashMap<String, List<PicinfoList>>();
	private ListAdapter adapterTest;
	
	public MyFriendsView(PageManager manager) {
		super(manager);
	}
	@Override
	public View getView() {
		Log.i(TAG, "@Override getView");
		return casualListView;
	}
	@Override
	public void onCreate(Object extra) {
		super.onCreate(extra);
		Log.i(TAG, "onCreate");
		MyLog.info(MyFriendsView.class, "onCreate()");
		ctx = manager.getContext();
		SetstateManager.setRefresState(MyFriendsView.class, manager);
		username = CommonUtil.getUserName(ctx);
		casualListView = new ListView(ctx);
		casualListView.setBackgroundColor(Color.BLACK);
		casualListView.setCacheColorHint(0x00000000);
		casualListView.setScrollbarFadingEnabled(false);
		casualListView.setVerticalScrollBarEnabled(true);

		mImageList = new ArrayList<Integer>();
		mImageList2 = new ArrayList<Integer>();
		myFriendsList = new ArrayList<Integer>();

		myFriendsList.add(R.drawable.icon);
		myFriendsList.add(R.drawable.icon);
		mImageList.add(R.drawable.liu);
		mImageList.add(R.drawable.liu);
		mImageList.add(R.drawable.liu);
		mImageList.add(R.drawable.liu);

		mImageList2.add(R.drawable.icon);
		mImageList2.add(R.drawable.icon);
		mImageList2.add(R.drawable.icon);
		mImageList2.add(R.drawable.icon);
      //获取好友列表
        getFriends(username);
        casualListView.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				MyLog.info(getClass(), "单击我的好友itme");
				CommonUtil.setFriendName(friendList.get(position).slave);
				CommonUtil.setFriendNick(friendList.get(position).nick);
				try {
					SetstateManager.setBacktoState(MyFriendsView.class, manager);
					SetstateManager.setRefresState(MyFriendsPhotoView.class, manager);
					manager.activePage(MyFriendsPhotoView.class, null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * 获取好友列表
	 * @author Administrator
	 */
	private String getFriends(String username){
		String rspString = null;
		if(gson == null)
		  gson = new Gson();
		Task task = new GetFriendsTask(ctx,username,1,20,new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
			}
			@Override
			public void CallBack(String rspString) {
				try {
					MyLog.info(getClass(), "jsonData:" + rspString);
					rspString = "[" + rspString + "]";
					JSONArray array = new JSONArray(rspString.toString());
					JSONArray array_data;
					JSONObject obj = array.getJSONObject(0);
					if (obj.getBoolean("msg")) {
						String res_data = obj.getString("data");
						MyLog.info(getClass(),
								"data:" + res_data.toString());
						if("[]".equals(res_data.toString())){
							handler.sendEmptyMessage(FRIEND_NO);
							return;
						}
						array_data = new JSONArray(res_data.toString());
						for (int i = 0; i < array_data.length(); i++) {
							FriendsInfo user = new FriendsInfo();
							JSONObject obj_data = array_data.getJSONObject(i);
							user.setMaster(obj_data.getString("master"));
							user.setIcon(obj_data.getString("icon"));
							user.setCreated(obj_data.getString("created"));
							user.setNick(obj_data.getString("nick"));
							user.setSlave(obj_data.getString("slave"));
							user.setStatus(obj_data.getString("status"));
							friendList.add(user);
						}
						Message ms = new Message();
						ms.what = FRIEND_INFO;
						handler.sendMessage(ms);
					} else {
						RondomUser info=new RondomUser();
						info.setErrCode(obj.getString("errCode"));
						Message ms = new Message();
						ms.what = FRIEND_FAIL;
						ms.obj = info;
						handler.sendMessage(ms);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(INTENT_ERROR);
			}
		});
		dialog_1 = ProgressDialog.show(ctx, "", ctx.getText(R.string.get_frineds), true);
		dialog_1.setCancelable(true);
		task.doTask(task);
		return rspString;
	}
	/**
	 * 获取相册列表
	 */
	private void getPicinfolist(final String username) {
		MyLog.info(getClass(), "getPicinfolist username:"+username);
		if (gson == null) {
			gson = new Gson();
		}
		Task task = new GetPicinfolistTask(ctx,username, 0,0, null,
				new ICallBack() {
					@Override
					public void CallBack(String imageUrl, Bitmap bm) {
					}
					@Override
					public void CallBack(String rspString) {
						// TODO Auto-generated method stub
						MyLog.info(getClass(), "jsonData:" + rspString);
						rspString = "[" + rspString + "]";
						JSONArray array;
						JSONArray array_data;
						List<PicinfoList> picinfoList;
						try {
							picinfoList = new ArrayList<PicinfoList>();
							array = new JSONArray(rspString.toString());
							JSONObject obj = array.getJSONObject(0);
							if (obj.getBoolean("msg")) {
								String res_data = obj.getString("data");
								MyLog.info(getClass(),
										"data:" + res_data.toString());
								if("[]".equals(res_data.toString())){
									handler.sendEmptyMessage(PICINFOLIST_INFO_FAIL);
									return;
								}
								array_data = new JSONArray(res_data.toString());
								for (int i = 0; i < array_data.length(); i++) {
									JSONObject obj_data = array_data.getJSONObject(i);
									MyLog.info(getClass(),"exif:" + obj_data.toString());
									PicinfoList info = new PicinfoList();
									info.setId(obj_data.getString("id"));
//									info.setFileid(obj_data.getString("fileid"));
									info.setPassport(obj_data.getString("passport"));
//									info.setPublic_(obj_data.getString("public"));
//									info.setTypeid(obj_data.getString("typeid"));
									info.setUpload_time(obj_data.getString("upload_time"));
//									info.setTitle(obj_data.getString("title"));
//									info.setContent(obj_data.getString("content"));
//									info.setViews(obj_data.getString("views"));
//									info.setScore(obj_data.getString("score"));
//									info.setBlock(obj_data.getString("block"));
//									info.setArea(obj_data.getString("area"));
//									info.setCoordinate(obj_data.getString("coordinate"));
									info.setPath_image(obj_data.getString("web_path"));
//									info.setHash_code(obj_data.getString("hash_code"));
									MyLog.info(getClass(),
											"pricinfolist:" + info.getTypeid());
									ProviderUtil.insertOrUpdatePicinfoList(ctx, info);
									picinfoList.add(info);
								}
								userMap.put(username, picinfoList);
								Message ms = new Message ();
								ms.what = PICINFOLIST_INFO;
								ms.obj =  picinfoList;
								handler.sendMessage(ms);
							} else {
								PicinfoList info = new PicinfoList();
								info.setErrCode(obj.getString("errCode"));
								Message ms = new Message ();
								ms.what = PICINFOLIST_INFO_FAIL;
								ms.obj = info;
								handler.sendMessage(ms);
							}
							
						} catch (JSONException e) {
							if (dialog_1 != null && dialog_1.isShowing())
								dialog_1.dismiss();
							e.printStackTrace();
						}
					}
					@Override
					public void TimeOut() {
						//网络超时处理
						handler.sendEmptyMessage(TIME_OUT);
					}
					@Override
					public void HttpError(int errorCode) {
						// TODO Auto-generated method stub
						handler.sendEmptyMessage(INTENT_ERROR);
					}
				});
		task.doTask(task);
	}
	/**
	 * 下载图片
	 * @param filenameList
	 */
   private void downMyPtoImage(List<String> filenameList,final String username){
   	final List<Bitmap> piclist = new ArrayList<Bitmap>();
   	Task task = new DownImageTask(ctx, username, filenameList, true, new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
				//发handler 做刷新操作
				MyLog.info(getClass(), "image bm:"+bm);
				if(bm != null){	
			    piclist.add(bm);
				//SetstateManager.setPicMapState(username,piclist);//添加到状态机制 供查看单张图片
				Message ms = new Message();
				ms.what = PICINFOLIST_RE_MYPTO_IMAGE;
				ms.obj = bm;
				handler.sendMessage(ms);
				}else{
					Message ms = new Message();
					ms.what = PICINFOLIST_DOWN_IMAGE_FAIL;
				    handler.sendMessage(ms);
				}
			}
			@Override
			public void CallBack(String rspString) {
			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
		});
   	task.doTask(task);
   }
   /**
    * 处理ui界面
    */
   private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
//				case 2:
//					//Log.w("---------------", "不断执行"+msg.what);
//					scrollView.smoothScrollBy(1500, 0);
//					//scrollView.scrollBy(150, 0);
//					break;
				case FRIEND_INFO://获取到好友信息
					  if (dialog_1 != null && dialog_1.isShowing())
							dialog_1.dismiss();
					adapterTest = new ListAdapter(ctx,userMap);
				    casualListView.setAdapter(adapterTest);
					for (FriendsInfo info : friendList) {
						MyLog.info(getClass(), "好友用户：" + info.getSlave());
						//获取用户图片
						//getPicinfolist(info.getSlave());
					}
					break;
				case FRIEND_NO: //没有好友信息
					MessageDialog.showToast(ctx, false,
							ctx.getString(R.string.no_friend));
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					adapterTest = new ListAdapter(ctx,FRIEND_NO);
				    casualListView.setAdapter(adapterTest);
					break;
				case FRIEND_FAIL: //获取好友信息失败
					RondomUser infoFail = (RondomUser) msg.obj;
					MessageDialog.showToast(ctx, false,
							ErrorInfo.errorMap.get(infoFail.getErrCode()));
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					break;
				case PICINFOLIST_INFO:
						//下载随便看看相片
					//List<PicinfoList> picinfoList = (List<PicinfoList>)msg.obj;
							
								//刷新界面
					break;
				case PICINFOLIST_INFO_FAIL:// 获取相册失败
					PicinfoList picInfo_fail = (PicinfoList)msg.obj;
					MessageDialog.showToast(ctx, false,ErrorInfo.errorMap.get(picInfo_fail.getErrCode()));
					break;
				case PICINFOLIST_RE_MYPTO_IMAGE:
					//做图片显示操作
					Bitmap bm = (Bitmap)msg.obj;
					//刷新界面
					adapterTest.notifyDataSetChanged();
					casualListView.setAdapter(adapterTest);
					break;
				case PICINFOLIST_DOWN_IMAGE_FAIL://下载图片失败
					//MessageDialog.showToast(ctx, false, ctx.getString(R.string.imagedown_doing_fail));
					break;
				case TIME_OUT://超时
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(ctx, false, ctx.getString(R.string.int_timeout));
					break;
				case INTENT_ERROR://网络错误
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(ctx, false, ctx.getString(R.string.int_error));
					break;
					}
			} catch (Exception e) {
			    e.printStackTrace();
			}
			}
	};
   
   
   
	private static class FriensHolder{
		ImageView userHead;
		TextView userName;
		TextView time;
		ImageView lookpto;
		ImageView addfriend;
		
		ImageView image_1;
		ImageView image_2;
		ImageView image_3;
		ImageView image_4;
		LinearLayout Layout;
		RelativeLayout RelativeLayout_list;
		LinearLayout imageLayout;
		LinearLayout layout_center;
		
	}
	 public class ListAdapter extends BaseAdapter{
	    	private Context mContext;
	    	private HashMap<String,List<PicinfoList>> userMap;
	    	private int no_friend = 0;
	    	private ListAdapter(Context context,HashMap<String,List<PicinfoList>> userMap){
	    		mContext = context;
	    		this.userMap = userMap;
	    		
	    	}
	    	private ListAdapter(Context context,int no_friend){
	    		mContext = context;
	    		this.no_friend = no_friend;
	    	}
		@Override
		public View getView( int position, View convertView, ViewGroup parent) {
			Log.i(TAG, "ListAdapter getView()");
			final FriensHolder holder;
			if (convertView == null) {
				holder = new FriensHolder();
				convertView = LayoutInflater.from(mContext)
						.inflate(R.layout.myfriend_image_list, null);
				holder.Layout = (LinearLayout) convertView
				.findViewById(R.id.LinearLayout_list);
				holder.RelativeLayout_list = (RelativeLayout) convertView
				.findViewById(R.id.RelativeLayout_list);
				//holder.layout_center =(LinearLayout)convertView .findViewById(R.id.layout_center); 
				holder.userHead = (ImageView) convertView
						.findViewById(R.id.image_head);
				holder.userName = (TextView) convertView
				.findViewById(R.id.user_name);
				holder.time = (TextView) convertView
				.findViewById(R.id.user_time);
				holder.lookpto = (ImageView) convertView
						.findViewById(R.id.lookpto);
				holder.image_1 = (ImageView) convertView
				.findViewById(R.id.image_1);
				holder.image_2 = (ImageView) convertView
				.findViewById(R.id.image_2);
				holder.image_3 = (ImageView) convertView
				.findViewById(R.id.image_3);
				holder.image_4 = (ImageView) convertView
				.findViewById(R.id.image_4);
				convertView.setTag(holder); 
			} else {
				holder = (FriensHolder) convertView.getTag();
			}
//				//长按操作
				holder.userHead.setOnLongClickListener(new View.OnLongClickListener() {
					
					@Override
					public boolean onLongClick(View v) { 
						MyLog.debug(getClass(), "onLongClick...");
						holder.lookpto.setVisibility(View.VISIBLE);
						return true;
					}
				});
				holder.userName.setOnLongClickListener(new View.OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						holder.lookpto.setVisibility(View.VISIBLE);
						return true;
					}
				});
				holder.RelativeLayout_list.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Log.i(TAG, "单击消失");
							if(holder.lookpto.getVisibility()==View.VISIBLE)
								holder.lookpto.setVisibility(View.GONE); 
						}
					});
				//点击查看相片
				holder.lookpto.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						try {
							manager.activePage(PicinfoView.class, null);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				convertView.setTag(holder);
				
				if(no_friend == FRIEND_NO){
					holder.userName.setText(ctx.getString(R.string.no_friend));
				}else{
				if (friendList != null && friendList.size() > 0)
					//设置昵称
				holder.userName.setText(friendList.get(position).getNick());
				//设置头像
				Bitmap bm =null;
					//bm=	CommonUtil.loadBitMap(mContext, userRanList.get(position).getHead_path());//下载头像
				if(bm == null){
				InputStream is = manager
						.getContext()
						.getResources()
						.openRawResource(
								R.drawable.icon);
				bm = BitmapFactory.decodeStream(is);
				bm = CommonUtil.getRoundedCornerBitmap(bm);
				}
				holder.userHead.setImageBitmap(bm);
				//设置时间
				holder.time.setText("9月1日");
				
				
				MyLog.info(getClass(), "position:"+position);
				//设置四张相片
				setImage(holder,null,null);
//				 List<PicinfoList>	picinfoList = userMap.get(friendList.get(position).getSlave());
//					//MyLog.info(getClass(), "username=" + friendList.get(position).getSlave() + ",picinfoList size=" + picinfoList.size());
//				List<String> imagelist =null;
//				if (picinfoList != null) {
//					imagelist = new ArrayList<String>();
//					for (PicinfoList info : picinfoList) {
//						imagelist.add(info.getPath_image());
//					}
//					if(imagelist != null && imagelist.size() >0)
//					downMyPtoImage(imagelist,username);
//				}
				}
			return convertView;
		}
		@Override
		public int getCount() {
			if(no_friend == FRIEND_NO)
				return 1;
			  else
			return friendList.size();
		}
		@Override
		public Object getItem(int position) {
			return position;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		
	}
	 /**
	  * 加载随即好友相片
	  * @author Administrator
	  *
	  */
	public void setImage(FriensHolder holder,Bitmap bm,List<Bitmap> bmlist) {
		// 加载好友照片
		Log.i(TAG, "**************setImage()******************");
		try {
//			
			if (mImageList != null && mImageList.size() > 0) {
				int image_1 = mImageList.get(0);
				int image_2 = mImageList.get(1);
				int image_3 = mImageList.get(2);
				int image_4 = mImageList.get(3);
		    
		if (holder.image_1 != null)
			holder.image_1.setImageBitmap(getBitmap(image_1));
			//holder.image_1.setImageBitmap(getBitmap(list.get(0).toString()));
		if (holder.image_2 != null)
			holder.image_2.setImageBitmap(getBitmap(image_2));
			//holder.image_2.setImageBitmap(getBitmap(list.get(1).toString()));
		if (holder.image_3 != null)
			holder.image_3.setImageBitmap(getBitmap(image_3));
			//holder.image_3.setImageBitmap(getBitmap(list.get(2).toString()));
		if (holder.image_4 != null)
			holder.image_4.setImageBitmap(getBitmap(image_4));
			//holder.image_4.setImageBitmap(getBitmap(list.get(3).toString()));
			}
//				View selectedView =  LayoutInflater.from(ctx)
//				.inflate(R.layout.grid_item, null);
//				ImageView imageView = (ImageView) selectedView
//						.findViewById(R.id.griditem);
//				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//						130, 110);
//				layoutParams.setMargins(0, 0, 7, 0);
//				selectedView.setLayoutParams(layoutParams);
////				InputStream is = manager
////						.getContext()
////						.getResources()
////						.openRawResource(pic);
////				Bitmap bm = BitmapFactory.decodeStream(is);
//				setImageClickListener(imageView, bm);
//				if (imageView != null)
//					imageView.setImageBitmap(bm);
//				holder.imageLayout.addView(selectedView);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public Bitmap getBitmap(int imageid){
		InputStream is = manager
		.getContext()
		.getResources()
		.openRawResource(imageid);
	    Bitmap bm = BitmapFactory.decodeStream(is);
	    bm = Bitmap.createScaledBitmap(bm, CommonUtil.width/4, 100,
				true);// 预先缩放，避免实时缩放，可以提高更新率
	  return bm;
	}
//	public void testUi(){
//		handler.post(runnable);
//		View selectedView;
//		for (Object o : list) {
//			Log.i(TAG,
//					"getView list: " + list.size() + ","
//							+ o.toString());
//			selectedView = ((Activity) mContext)
//					.getLayoutInflater().inflate(
//							R.layout.grid_item, null);
//			ImageView imageView = (ImageView) selectedView
//					.findViewById(R.id.griditem);
//			final int pic = Integer.parseInt(o.toString());
//			imageView.setOnClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					try {
//						
////						PicinfoActivity.setPic(pic);
////						Intent intent = new Intent();
////						intent.setClass(ctx, PicinfoActivity.class);
////						ctx.startActivity(intent); 
//						PicinfoView.setPic(pic);
//						manager.activePage(PicinfoView.class, null);
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
//			});
//			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//					130, 110);
//			layoutParams.setMargins(0, 0, 7, 0);
//			selectedView.setLayoutParams(layoutParams);
//			InputStream is = manager
//					.getContext()
//					.getResources()
//					.openRawResource(pic);
//			Bitmap bm = BitmapFactory.decodeStream(is);
//			if (imageView != null)
//				imageView.setImageBitmap(bm);
//			mLayout.addView(selectedView);
//		}
//		list.clear();
//	} 
//	public void clearImageList() {
//		// 把已经存储的已选择图片的缩略图回收
//		if (mImageList != null && mImageList.size() > 0) {
//			for (int i = 0, l = mImageList.size(); i < l; i++) {
//				InputStream is = manager
//						.getContext()
//						.getResources()
//						.openRawResource(
//								Integer.parseInt(mImageList.get(i).toString()));
//				Bitmap bm = BitmapFactory.decodeStream(is);
//				if (bm != null && !bm.isRecycled()) {
//					bm.recycle();
//				}
//			}
//			mImageList.clear();
//		}
//	}
//	
//	private Runnable runnable = new Runnable() {
//
//		@Override
//		public void run() {
//			// TODO Auto-generated method stub
//			 
//			Message msg = handler.obtainMessage();
//			msg.what = 2;
//			handler.sendMessage(msg);
//		}  
//		
//	};
}

